/**
 * @author kidy
 */

var QS_MarketBarometer = function(callback){
    this.HTML = '<div class="qs_marketbarometer"><div class="qs-marketbarometerwrap">' +
	    '<div class="style-main">' +
	        '<div class="main" style="overflow:hidden;">' +
	          '<div class="1d box"></div>' +
	          '<div class="clorbox"></div>' +
	        '</div>' +
	        '<div class="center-gap"></div>' +
	        '<div class="sub">' +
	            '<div class="1w box"></div>' +
	            '<div class="1m box"></div>' +
	            '<div class="3m box"></div>' +
	            '<div class="1y box"></div>' +
	            '<div class="3y box"></div>' +
	        '</div>' +
		'</div>' +
		'<div class="grid-list"></div></div>' +
    '</div>';
    this.tValidation=null;
    this.lastHeightChange=0;
    this.firstTag=true;
    this.colorbox = null;
    this._textKey = document.body.textContent ? 'textContent' : 'innerText';
    this.staticValue={
    	realTime:"1d",
    	centerGap:10,
    	mainBox:120,
    	subBox: 35,
    	minWidth:180,
    	winTitle:26
    }
    this.mainBox = null;
    this.msStyleBoxs = [];
	this.profile = {
		dayRange:'1d',
		isAPI:true,
		fixHeight:true,
		rangeMap: {'1d':'Day','1w':'1Wk','1m':'1Mo ','3m':'3Mo','1y':'1Yr','3y':'3Yr'},
		colorRange: {'1d':1.25,'1w':1.25,'1m':4,'3m':8,'1y':20,'3y':20},
		dtgrid:true,
		decimal:2,
		clickable:true,
		showRtn:true,//display chg% in td
		columns: [{
			header: "Morningstar Indexes",
			dataIndex: 'symbols',
			width: '75%',
			dataType: 'string'
		}, {
			header: "Return%",
			dataIndex: 'dChg%',
			width: '25%',
			align: 'right',
			dataType: 'string'
		}]
	};
	this.callback = callback||{};
	this.dtgrid=null;
	this.scrollPanel = null;
	this.symbols={
		'MLCR':{
			"symbols":"Large Core",
			"dayticker":"$MLCR",
			"totalticker":"$MLCRT"
		}, 
		'MLGR':{
			"symbols":"Large Growth",
			"dayticker":"$MLGR",
			"totalticker":"$MLGRT"
		},
		'MLVL':{
			"symbols":"Large Value",
			"dayticker":"$MLVL",
			"totalticker":"$MLVLT"
		},

		'MMCR':{
			"symbols":"Mid Core",
			"dayticker":"$MMCR",
			"totalticker":"$MMCRT"
		}, 
		'MMGR':{
			"symbols":"Mid Growth",
			"dayticker":"$MMGR",
			"totalticker":"$MMGRT"
		}, 
		'MMVL':{
			"symbols":"Mid Value",
			"dayticker":"$MMVL",
			"totalticker":"$MMVLT"
		}, 
		
		'MSCR':{
			"symbols":"Small Core",
			"dayticker":"$MSCR",
			"totalticker":"$MSCRT"
		}, 
		'MSGR':{
			"symbols":"Small Growth",
			"dayticker":"$MSGR",
			"totalticker":"$MSGRT"
		},
		'MSVL':{
			"symbols":"Small Value",
			"dayticker":"$MSVL",
			"totalticker":"$MSVLT"
		}
	};
}

QS_MarketBarometer.prototype = {
    init: function(ContainerId, Profile, Sid){
        this.containerId = ContainerId;
        this.container = $('#' + ContainerId),this.id = Sid;
        $.extend(this.profile, Profile);
        $.extend(this.callback, Profile.callback);
        QS_MSStyleBoxDataManager.registerGrid(Sid,this);
		this._createTickers();
        this.el = $(this.HTML);
        this.el.appendTo(this.container);
        this.colorbox = new QS_MSStyleBoxcolorGroup(this.el.find('.clorbox'), {colors:this.profile.colors});
        this.initMSStyleBoxs();
		if(this.profile.width){
			this.el.css({width:this.profile.width});
		}
		if(!this.profile.isAPI&&!isNaN(this.profile.height)){
            this.profile.height-=this.staticValue.winTitle;
        }  
		this.scrollPanel = new Util.ScrollPanel(this.el.find(".qs-marketbarometerwrap"),{showX:false,showY:this.profile.fixHeight});
		if(this.profile.dtgrid) {
			this.initDTGrid();
		}else{
			var self=this;
			Util.DelayRun('heightchange.marketbarometer', self.heightChangeHandler, 100, self);//for triggle onLoad
		}
		//init
		this.bindGrid();
		QS_MSStyleBoxDataManager.updateColor(this.id);
		var self=this;
		QS_MSStyleBoxDataManager.getHistoryData({ticker:this.totalTickers},function(){
			QS_MSStyleBoxDataManager.setInterval({ticker:self.dayTickers});
		});
		this.bindEvent();
    },
    setMinWidth:function(width){
    	if(typeof width!='undefined'&& !isNaN(width)){
	    	this.staticValue.minWidth=width;
	    }
    },
    _createTickers:function(){
    	this.dayTickers=[],this.totalTickers=[];
    	for(var ticker in this.symbols){
    		this.dayTickers.push(this.symbols[ticker]["dayticker"]);
    		this.totalTickers.push(this.symbols[ticker]["totalticker"]);
    	}
    },
    saveConfig:function(){
        return null;
    },
    clear:function(){
        QS_MSStyleBoxDataManager.unregister(this.id);
        QS_MSStyleBoxDataManager.unregisterGrid(this.id);
        for (var p in this) {
            if (!p || p == 'clear') {
                continue;
            }
            this[p] = null;
            delete this[p];
        }
    },
    initDTGrid: function(){
    	var self=this;
		var columns=[{
			header: "rowid",
			dataIndex: 'rowid',
			width: 0,
			dataType: 'string',
			hide: true
		}].concat(this.profile.columns);
		this.dtgrid = new Util.DataGrid(this.el.find('.grid-list'), {}, {
			column: columns,
			autoWidth: true,
			autoHeight: true,
			sortable: false,
			cellRearrange: false,
			htmlLayer: 'div',
			//headerRow: false,
			rowDragable: false,
			rowDropable: false
		}, {afterRebindData: function(DOMMap, rows){
	            Util.DelayRun('heightchange.marketbarometer', self.heightChangeHandler, 100, self);
	        }});
		QS_MSStyleBoxDataManager.registerGrid(this.id,this);
	},
	bindEvent:function(){
		var self = this, styleBoxContainers = this.el.find('.sub .box');
		styleBoxContainers.bind('mouseenter',function(){
			self.profile.dayRange = this.className.substr(0,2);
			Util.DelayRun('updateGrid.marketbarometer', self.bindGrid, 200, self);
		});
		this.el.find('.sub').bind('mouseleave',function(){
			self.profile.dayRange = self.staticValue.realTime;
			Util.DelayRun('updateGrid.marketbarometer', self.bindGrid, 200, self);
		});
	},
	getRange:function(){
		return this.profile.dayRange;
	},
    initMSStyleBoxs: function(){
        this.mainBox = new QS_MSStyleBox(this.el.find(".style-main .main ." + this.staticValue.realTime), {
			type: this.staticValue.realTime,
			label: this.profile.rangeMap[this.staticValue.realTime],
			scope: this.profile.colorRange[this.staticValue.realTime],
			width:this.staticValue.mainBox,
			showRtn: this.profile.showRtn,
			showRangeTitle: false,
			showHeader: true,
			category:this.id,
			clickable: this.profile.clickable,
			callback: this.callback
		}, this.colorbox);
		QS_MSStyleBoxDataManager.register(this.id,this.staticValue.realTime,this.mainBox);
        //var subContainers = this.el.find(".sub div");
        for (var dayrange in this.profile.rangeMap) {
        	if(dayrange ==this.staticValue.realTime) continue;
            var subbox = new QS_MSStyleBox(this.el.find(".style-main .sub ." + dayrange), {
            	type: dayrange,
                scope: this.profile.colorRange[dayrange],
                width: this.staticValue.subBox,
                showRangeTitle: true,
                category:this.id,
                label:this.profile.rangeMap[dayrange]
            }, this.colorbox);
            QS_MSStyleBoxDataManager.register(this.id,dayrange,subbox);
            this.msStyleBoxs.push(subbox);
        }
    },
    //for QS_DataManager
    updateData: function(gKey, aData,needFlash){
    	QS_MSStyleBoxDataManager.refreshStyleBox(this.id,this.staticValue.realTime,false);
    	if(this.profile.dayRange == this.staticValue.realTime){
    		QS_MSStyleBoxDataManager.showRange(this.id,this.staticValue.realTime);
    		if(this.profile.dtgrid){
    			for(var field in aData){
					this._updateDOM(gKey, field, aData[field].value, aData[field].ovalue,needFlash);
    			}
	    	}
    	}
    },
    _updateDOM:function(gkey,gridField,value,oldvalue,needFlash){
    	if (!this.dtgrid.DOMMap[gkey]) {
            return;
        }
        var el = this.dtgrid.DOMMap[gkey][gridField];
        if(!el) return;
        var _flashMethod = needFlash === false ? function(){}: flash,contentKey = this._textKey;
        _flashMethod(el,value,oldvalue);
        el[contentKey] = this._toDecimal(value);
    },
	bindGrid:function(){
		if(!this.profile.dtgrid) return;
		var data=[],gdata=QS_MSStyleBoxDataManager.getData(this.profile.dayRange).data;
        for (var gkey in gdata) {
			data.push({
				'rowid': gkey,
				'symbols': this.symbols[gkey]["symbols"],
				'dChg%': this._toDecimal(gdata[gkey])
			});
		}
        this.dtgrid.reBindData(data);
	},
	_toDecimal:function(data){
		return data.toFixed(this.profile.decimal);
	},
    changeOutSize: function(w, h){
    	if(this.profile.isAPI){
    		w = this.profile.width||w||this.container.width();
    		h = this.profile.height||h||this.container.height();
        }else{
            //if it is terminal, the height of win-bd is static
            w = w||this.container.parent().width();
            h = h||this.container.parent().height();
            this.el.css({
                width: "auto"
            });
        }
		w =Math.max(this.staticValue.minWidth,w);
		if(this.profile.fixHeight){
			this.scrollPanel.reSize(w, h);
		}else{
			this.scrollPanel.reSize(w, null);
			h = this.el.height();
		}
		this.heightChangeHandler(h);
	},
	heightChangeHandler:function(h){
		var height=h||this.el.height();
		if (this.firstTag) {
			this.firstTag=false;
            this.lastHeightChange = height;
            if (typeof this.callback.onLoad == 'function') {
				this.callback.onLoad({
					component: 'marketBarometer',
					height: height,
					minWidth: this.staticValue.minWidth
				});
			}
        }else {
            if (this.lastHeightChange != height) {
                this.lastHeightChange = height;
                if (typeof this.callback.onHeightChange == 'function') {
                    this.callback.onHeightChange({
                        height: height,
                        component: 'marketBarometer',
						minWidth: this.staticValue.minWidth
                    });
                }
            }
        }
	}
};